<template>
    <div class="agent">
      <van-nav-bar safe-area-inset-top placeholder :title="userName" fixed @click-left="openMenu">
        <template #left>
          <van-icon name="ellipsis" size="24" />
        </template>
      </van-nav-bar>
      <van-popup v-model="show" position="left" :style="{width:'200px',height:'100%'}">
        <van-tabbar>
          <van-tabbar-item @click="logOut">{{$t('logOut')}}</van-tabbar-item>
        </van-tabbar>
      </van-popup>
      <van-pull-refresh v-model="isLoading" :pulling-text="$t('PullingText')" :loosing-text="$t('PullingText')" :success-text="$t('refreshSuccee')" @refresh="onRefresh">
        <div class="agentTopTableBar-box">
          <div class="main-box">
            <div @click='goto("agent")'>{{$t('Agent')}}<div class="contain">{{datas.agent}}</div></div>
            <div @click='goto("user")'>{{$t('User')}}<div class="contain">{{datas.user}}</div></div>
            <div @click='goto("inverter")'>{{$t('Inverter')}}<div class="contain">{{datas.dev}}</div></div>
            <div @click='goto("sites")'>{{$t('Site')}}<div class="contain">{{datas.site}}</div></div>
          </div>
        </div>
        <div class="cart-box">
          <div class="time-box">
            <div class="title">{{$t('Yield')}} (kWh)</div>
            <div class="sel" @click="showPicker1 = true">{{value1.name}}</div>
            <van-popup v-model="showPicker1" round position="bottom">
              <van-picker show-toolbar :columns="allTime" value-key='name'
                @cancel="showPicker1 = false"
                @confirm="onConfirm1"
                :confirm-button-text="$t('OK')"
                :cancel-button-text="$t('Cancel')"
              />
            </van-popup>
          </div>
          <div class="record-box">
            <div>
              <div class="button-green button-style">{{$t('Month')}}</div> 
              <div style="color: #799F2D;">{{YMtDataList.monthYield | numFilter(1)}}</div>
            </div>
            <div>
              <div class="button-purple button-style">{{$t('Year')}}</div> 
              <div style="color: #7F699B;">{{YMtDataList.yearYield | numFilter(1)}}</div>
            </div>
            <div>
              <div class="button-orange button-style">{{$t('Total')}}</div>
              <div style="color:#F9BC3C;">{{YMtDataList.totalYield | numFilter(1)}}</div>
            </div>
          </div>
          <div id="agentEchart" :style="{width: '100%', height: '280px'}"></div>
        </div>
        <div class="cart-box">
            <div class="time-box">
              <div class="title">{{$t('SalesAnalysis')}}</div>
              <div class="sel" @click="showPicker2 = true">{{value2.name}}</div>
              <van-popup v-model="showPicker2" round position="bottom">
                  <van-picker show-toolbar :columns="salesTime"
                  value-key='name'
                  @cancel="showPicker2 = false"
                  @confirm="onConfirm2"
                  :confirm-button-text="$t('OK')"
                  :cancel-button-text="$t('Cancel')"
                  />
              </van-popup>
            </div>
            <div class="record-box">
                <div>
                  <div class="button-green button-style">{{$t('Month')}}</div> 
                  <div style="color: #799F2D;">{{salesTotalData.month}}</div>
                </div>
                <div>
                  <div class="button-purple button-style">{{$t('Year')}}</div> 
                  <div style="color: #7F699B;">{{salesTotalData.year}}</div>
                </div>
                <div>
                  <div class="button-orange button-style">{{$t('Total')}}</div>
                  <div style="color:#F9BC3C;">{{salesTotalData.total}}</div>
                </div>
            </div>
            <div id="salesEchart" :style="{width: '100%', height: '280px'}"></div>
        </div>
      </van-pull-refresh>
    </div>
</template>

<script>
import moment from 'moment'
export default {
  data() {
    return {
      show:false,
      userName:localStorage.getItem('userName'),
      isLoading:false,
      datas:{},
      YMtDataList:{},
      showPicker1:false,
      allTime:[
        {name:this.$t('Day'),reportType:1},
        {name:this.$t('Month'),reportType:2},
        {name:this.$t('Year'),reportType:3},
        {name:this.$t('AllYear'),reportType:4}
      ],
      showPicker2:false,
      salesTime:[
        {name:this.$t('Month'),reportType:0},
        {name:this.$t('Year'),reportType:1},
        {name:this.$t('AllYear'),reportType:2}
      ],
      value1:{
        name:this.$t('Day'),
        reportType:1
      },
      value2:{
        name:this.$t('Month'),
        reportType:0
      },
      salesTotalData:{},
      salesechartDataList:[],
      fifteenRefresh:null
    };
  },
  methods: {
    openMenu(){
      this.show=true;
    },
    logOut(){
      if(!localStorage.getItem('remember')){
        localStorage.removeItem('password');
      }
      localStorage.removeItem('tokenId');
      localStorage.removeItem('userId');
      localStorage.removeItem('role');
      localStorage.removeItem('siteId');
      localStorage.removeItem('siteName');
      this.$router.push({path:'/login'});
    },
    goto(url){
        this.$router.push({path:'/agentHome/'+url,});
    },
    onConfirm1(value) {
      this.showPicker1 = false;
      this.value1 = value;
      this.agentGetYield();
    },
    onConfirm2(value) {
      this.showPicker2 = false;
      this.value2 = value;
      this.saleStatisticsByTime();
    },
    async getCountInfo(){
      let res = await this.API.getCountInfo(localStorage.getItem("domain"),{
        tokenId:localStorage.getItem("tokenId")
      })
      this.datas = res.result;
    },
    async getTimeYield(){
      let res = await this.API.getTimeYield(localStorage.getItem("domain"),{
          tokenId:localStorage.getItem("tokenId"),
          currentTime:moment(new Date()).format('YYYY-MM-DD')
      })
      this.YMtDataList = res.result;
    },
    async agentGetYield(){
      this.comm.loadingShow();
      let data = await this.API.agentGetYield(localStorage.getItem("domain"),{
          tokenId:localStorage.getItem("tokenId"),
          reportType:this.value1.reportType,
          day:moment(new Date()).format('D'),
          month:moment(new Date()).format('M'),
          year:moment(new Date()).format('YYYY'),
          webTime:moment(new Date()).format('YYYY,M,D')
      });
      let arrX=[],arrY=[];
      if(data.success){
        for(let i= 0;i<(data.result).length;i++){
          arrX.push((data.result)[i].time);
          if((data.result)[i].yieldtoday!=null||(data.result)[i].yieldtoday!=undefined){
            arrY.push(((data.result)[i].yieldtoday).toFixed(2));
          }
        }
        this.initEcharts(arrX,arrY);
      }
    },
    async saleStatistics(){
      let res = await this.API.saleStatistics(localStorage.getItem("domain"),{
        tokenId: localStorage.getItem("tokenId"),
        currentTime:moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
      })
      this.salesTotalData = res&&res.result;
    },
    async saleStatisticsByTime(){
      this.comm.loadingShow();
      let data = await this.API.saleStatisticsByTime(localStorage.getItem("domain"),{
        tokenId: localStorage.getItem("tokenId"),
        currentTime: moment(new Date()).format('YYYY-MM-DD'),
        timeType:this.value2.reportType
      });
      let arrX=[],arrY=[];
      if(data.success){
        for(let i= 0;i<(data.result).length;i++){
          arrX.push((data.result)[i].time);
          arrY.push((data.result)[i].sum);
        }
        this.initEchartsLine(arrX,arrY);
      }
    },
    initEcharts(arrX,arrY){
      let myChart = this.$echarts.init(document.getElementById('agentEchart'));
      let echartsid = document.getElementById('agentEchart');
      myChart.setOption({
        color:['#F7AB00'],
        title: {
          show: arrX.length != 0?false:true,
          extStyle: {
            color: "#7d7d7d",
            fontSize: 20
          },
          text: this.$t('NoData'),
          left: "center",
          top: "center"
        },
        tooltip : {
          trigger: 'axis',
          axisPointer: {
            lineStyle: {
              color: '#cccccc'
            }
          },
          formatter:(data)=>{
            let relVal="";
            if(this.value1.reportType == 1){
              relVal=moment(new Date()).format('YYYY-MM-DD')+" "+data[0].name+":00"+"<br/>"+data[0].seriesName+" : "+data[0].value+"kWh";
            }else if(this.value1.reportType == 2){
              relVal=moment(new Date()).format('YYYY-MM')+"-"+data[0].name+"<br/>"+data[0].seriesName+" : "+data[0].value+"kWh";
            }else if(this.value1.reportType == 3){
              relVal=moment(new Date()).format('YYYY')+"-"+data[0].name+"<br/>"+data[0].seriesName+" : "+data[0].value+"kWh";
            }else{
              relVal=data[0].name+"<br/>"+data[0].seriesName+" : "+data[0].value+"kWh";
            }
            return relVal;
          }
        },
        grid: {
          x:5,
          x2:5,
          y:20,
          y2:10,
          containLabel: true
        },
        xAxis : [
          {
            type : 'category',
            axisLabel: {
              show:true,
              textStyle:{
                color:'#7F7F7F'
              }
            },
            axisLine:{
              show:false
            },
            axisTick:{
              show:false
            },
            data : arrX
          }
        ],
        yAxis : [
          {
            type : 'value',
            axisLabel: {
              show:true,
              textStyle:{
                color:'#525252'
              }
            },
            splitLine: {
              show:true,
              lineStyle:{
                color:'#C4C4C4',
                type:'dotted'
              }
            },
            axisLine:{
              show:false
            },
            axisTick:{
              show:false
            }
          }
        ],
        series : [
          {
            name:this.$t('Yield'),
            type:'bar',
            data:arrY
          }
        ]
      });
      window.addEventListener("resize", function() {
          myChart.resize();
      });
    },
    initEchartsLine(arrX,arrY){
      let myChart = this.$echarts.init(document.getElementById('salesEchart'));
      let echartsid = document.getElementById('salesEchart');
        myChart.setOption({
        title: {
          show: arrX.length != 0?false:true,
          extStyle: {
            color: "#7d7d7d",
            fontSize: 20
          },
          text: this.$t('NoData'),
          left: "center",
          top: "center"
        },
        tooltip : {
          trigger: 'axis',
          axisPointer: {
            lineStyle: {
              color: '#cccccc'
            }
          },
          formatter:(data)=>{
            let relVal2="";
            if(this.value2.reportType==0){
              relVal2=moment(new Date()).format('YYYY-MM')+"-"+data[0].name+"<br/>"+data[0].seriesName+" : "+data[0].value;
            }else if(this.value2.reportType==1){
              relVal2=moment(new Date()).format('YYYY')+"-"+data[0].name+"<br/>"+data[0].seriesName+" : "+data[0].value;
            }else{
              relVal2=data[0].name+"<br/>"+data[0].seriesName+" : "+data[0].value;
            }
            return relVal2;
          }
        },
        grid: {
          x:5,
          x2:20,
          y:20,
          y2:10,
          containLabel: true
        },
        xAxis: {
            type: 'category',
            axisLabel: {
              show:true,
              textStyle:{
                color:'#525252'
              }
            },
            axisLine:{
              show:true,
              lineStyle:{
                color:'#C4C4C4'
              }
            },
            axisTick:{
              show:false
            },
            data: arrX
        },
        yAxis: [
            {
            type : 'value',
            axisLabel: {
              show:true,
              formatter: '{value}',
              textStyle:{
                color:'#525252'
              }
            },
            splitLine: {
              show:true,
              lineStyle:{
                color:'#C4C4C4',
                type:'dotted'
              }
            },
            axisLine:{
              show:false
            },
            axisTick:{
              show:false
            }
          }
        ],
        series: [{
            name:this.$t('Sales'),
            type: 'line',
            itemStyle:{
            normal:{
              lineStyle:{
                color:'#F39800'
              },
              borderColor:'#F39800'
            }
          },
          data: arrY
        }]
      })
      window.addEventListener("resize", function() {
          myChart.resize();
      });
    },
    onRefresh(){
      this.isLoading=false;
      this.getCountInfo()
      this.getTimeYield()
      this.agentGetYield()
      this.saleStatistics()
      this.saleStatisticsByTime()
    }
  },
  mounted() {
    setTimeout(()=>{
      this.getCountInfo();
      this.getTimeYield();
      this.agentGetYield();
      this.saleStatistics();
      this.saleStatisticsByTime();
    },1000);
    this.fifteenRefresh=setInterval(()=>{
      this.getCountInfo();
      this.getTimeYield();
      this.agentGetYield();
      this.saleStatistics();
      this.saleStatisticsByTime();
    },900000);
  },
  destroyed(){
    clearInterval(this.fifteenRefresh);
    this.fifteenRefresh=null;
  }
};
</script>

<style lang="less">
.agent{
  .van-hairline--bottom::after{
    border: none;
  }
  .agentTopTableBar-box{
    width: 100%;
    .main-box{
        width: 100%;
        height: 60px;
        background-color: #3B3D4E;
        color: #fff;
        display: flex;
        align-items: center;
        div{
            flex: 1;
            .contain{
                padding-top: 5px;
            }
        }
    }
  }
  .cart-box{
    background-color: #fff;
    margin-top: 10px;
    padding:5px 10px;
  }
  .time-box{
    width: 100%;
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid #e6e6e6;
    align-items: center;
    padding-bottom: 5px;
    .title{
      font-size: 14px;
    }
  }
  .sel{
    float: left;
    height: 30px;
    line-height: 30px;
    padding: 0 20px 0 10px;
    font-size: 14px;
    border: 1px solid #B6B6B8;
    border-radius: 15px;
    background: url("../../assets/xl.png") no-repeat right 5px top 12px;
    margin-left: 10px;
  }
  .record-box{
    display: flex;
    justify-content: space-around;
    align-items: center;
  }
  .button-green{
    background: #799F2D;
  }
  .button-purple{
    background: #7F699B;
  }
  .button-orange{
    background: #F9BC3C;
  }
  .button-style{
    width: 70px;
    height: 28px;
    text-align: center;
    line-height: 28px;
    margin: 10px auto;
    border-radius: 5px;
    color: #ffffff;
  }
}
</style>
